﻿using RXY_Mall.Application.Goods.Dto;
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Domain;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RXY_Mall.Application.Goods
{
    public class GoodsService : RXY_MallAppServiceBase, IGoodsService
    {
        #region 商品
        public async Task<Response<int>> AddorEditGoods(int managerId, GoodsInput input)
        {
            //TODO:数据验证
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(input.name))
            {
                errorList.Append("商品名称不能为空；</br>");
            }
            //if (string.IsNullOrEmpty(input.summary)|| input.summary.Trim().Length < 4|| input.summary.Trim().Length >20)
            //{
            //    errorList.Append("商品卖点4-20个字；</br>");
            //}
            if (string.IsNullOrEmpty(input.brand))
            {
                errorList.Append("品牌不能为空；</br>");
            }
            if (input.banner_img_List.Count == 0)
            {
                errorList.Append("请至少上传一张商品图片；</br>");
            }
            if (string.IsNullOrEmpty(input.short_title))
            {
                errorList.Append("请输入短标题；</br>");
            }
            if (input.type_id != 1 && input.settlement_price <= 0)
            {
                errorList.Append("请输入有效结算价；</br>");
            }
            if (input.sale_price < input.settlement_price)
            {
                errorList.Append("平台价不能低于结算价；</br>");
            }
            //if (input.freight_template_id==-1)
            //{
            //    errorList.Append("请选择运费模板；</br>");
            //}
            if (input.market_price < input.sale_price)
            {
                errorList.Append("市场价不能低于销售价；</br>");
            }
            if (input.red_packet >= 100)
            {
                errorList.Append("红包比例不能大于100%；</br>");
            }
            if (input.type_id != 3)
            {
                if (input.require_num < 3)
                {
                    errorList.Append("拼手气不能少于3人；</br>");
                }
                //if (input.duration < 1 || input.duration > 24)
                //{
                //    errorList.Append("时长最低为1小时最长为24小时；</br>");
                //}
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<int>(errorList.ToString());
            }
            List<int> goods_service_list = new List<int>();
            if (!string.IsNullOrEmpty(input.goods_service))
            {
                string[] gs = input.goods_service.Split(',');
                for (int i = 0; i < gs.Length; i++)
                {
                    if (Validator.IsInt(gs[i]))
                    {
                        goods_service_list.Add(int.Parse(gs[i]));
                    }
                }
            }
            if (input.id > 0)
            {
                var entity = db.gw_goods
                    .Include(i => i.gw_goods_property)
                    .Include(i => i.gw_goods_rule_free)
                    .Include(i => i.gw_goods_rule_group)
                    .FirstOrDefault(i => i.id == input.id);
                if (entity != null)
                {
                    entity.name = input.name;
                    entity.short_title = input.short_title;
                    if (input.freight_template_id > 0)
                    {
                        entity.freight_template_id = input.freight_template_id;
                    }
                    entity.weight = input.weight;
                    entity.summary = input.summary == null ? "" : input.summary;
                    entity.description = input.description == null ? "" : input.description;
                    entity.limit_quantity = input.limit_quantity;
                    entity.notify_admin_quantity = input.notify_admin_quantity;
                    entity.category_id = input.category_id;
                    entity.category_id1 = input.category_id1;
                    entity.category_id2 = input.category_id2;
                    entity.remark = input.remark == null ? "" : input.remark;
                    switch (entity.type_id)
                    {
                        case 1://拼手气
                            //entity.gw_goods_rule_group.group_price = input.sale_price;
                            entity.gw_goods_rule_group.red_packet = input.red_packet;
                            entity.gw_goods_rule_group.require_num = input.require_num;
                            entity.gw_goods_rule_group.duration = input.duration;
                            entity.gw_goods_rule_group.start_time = input.start_time;

                            if (input.end_time != null)
                            {
                                entity.gw_goods_rule_group.end_time = input.end_time;
                            }
                            break;
                        case 2://合力免单
                            entity.gw_goods_rule_free.require_num = input.require_num;
                            entity.gw_goods_rule_free.duration = input.duration;
                            entity.gw_goods_rule_free.start_time = input.start_time;

                            if (input.end_time != null)
                            {
                                entity.gw_goods_rule_free.end_time = input.end_time;
                            }
                            break;
                        case 4://1元购
                            entity.gw_goods_rule_free.require_num = input.require_num;
                            entity.gw_goods_rule_free.duration = input.duration;
                            entity.gw_goods_rule_free.start_time = input.start_time;

                            if (input.end_time != null)
                            {
                                entity.gw_goods_rule_free.end_time = input.end_time;
                            }
                            break;
                            //case 3://趣卡专享
                            //    break;
                    }
                    if (entity.gw_goods_property.settlement_price != input.settlement_price)
                    {
                        var sku = db.gw_goods_skus.Where(i => i.goods_id == entity.id && !i.deleted);
                        foreach (var item in sku)
                        {
                            item.settlement_price = input.settlement_price;
                        }
                    }
                    var settlement_price_is_change = false;
                    var sale_price_is_change = false;
                    settlement_price_is_change = entity.gw_goods_property.settlement_price != input.settlement_price;
                    sale_price_is_change = entity.gw_goods_property.sale_price != input.sale_price;
                    entity.gw_goods_property.settlement_price = input.settlement_price;
                    entity.gw_goods_property.sale_price = input.sale_price;
                    entity.gw_goods_property.market_price = input.market_price;
                    entity.gw_goods_property.service_rate = input.service_rate;
                    entity.gw_goods_property.is_new = input.is_new;
                    entity.gw_goods_property.is_top = input.is_top;
                    entity.gw_goods_property.sort = input.sort;
                    entity.update_time = DateTime.Now;
                    //商品服务
                    if (goods_service_list.Count > 0 && goods_service_list[0] > 0)
                    {
                        List<gw_goods_service> gsAddList = new List<gw_goods_service>();
                        List<gw_goods_service> gsDelList = new List<gw_goods_service>();
                        gw_goods_service gs = new gw_goods_service();
                        gsDelList = entity.gw_goods_service.ToList();
                        foreach (var item in goods_service_list)
                        {
                            if (item > 0)
                            {
                                gs = db.gw_goods_services.FirstOrDefault(i => i.id == item);
                                if (gs != null)
                                {
                                    if (!entity.gw_goods_service.Contains(gs))
                                    {
                                        gsAddList.Add(gs);
                                    }
                                    else
                                    {
                                        gsDelList.Remove(gs);
                                    }
                                }
                            }
                        }
                        foreach (var item in gsDelList)
                        {
                            entity.gw_goods_service.Remove(item);
                        }
                        foreach (var item in gsAddList)
                        {
                            entity.gw_goods_service.Add(item);
                        }
                    }
                    else
                    {
                        entity.gw_goods_service = null;
                    }
                    //品牌
                    if (!string.IsNullOrEmpty(input.brand))
                    {
                        var brand = db.gw_base_brands.FirstOrDefault(i => i.name == input.brand);
                        if (brand != null)
                        {
                            entity.category_id3 = brand.id;
                        }
                        else
                        {
                            var gw_base_brand = new gw_base_brand();
                            gw_base_brand.name = input.brand;
                            gw_base_brand.logo = "";
                            gw_base_brand.status = 1;
                            gw_base_brand.add_time = DateTime.Now;
                            var brand_model = db.gw_base_brands.Add(gw_base_brand);
                            await db.SaveChangesAsync();
                            entity.category_id3 = brand_model.id;
                        }
                    }
                    if (!db.gw_shop_brand_mappings.Any(i => i.shop_id == entity.shop_id && i.brand_id == entity.category_id3 && i.category_id == entity.category_id2))
                    {
                        var shop_brand = new gw_shop_brand_mapping();
                        shop_brand.shop_id = entity.shop_id;
                        shop_brand.brand_id = entity.category_id3;
                        shop_brand.category_id = input.category_id2;
                        db.gw_shop_brand_mappings.Add(shop_brand);
                    }
                    //图片
                    //TODO：删除已删除图片，已存在图片更新排序；图片由临时文件夹转移到正式文件夹goods/shopId/goodsId
                    var delList = entity.gw_goods_picture;
                    if (delList.Count() > 0)
                    {
                        db.gw_goods_pictures.RemoveRange(delList);
                    }

                    List<gw_goods_picture> banner_add = new List<gw_goods_picture>();
                    List<gw_goods_picture> info_add = new List<gw_goods_picture>();
                    var banner_img_count = input.banner_img_List == null ? 0 : input.banner_img_List.Count();
                    var info_img_count = input.info_img_List == null ? 0 : input.info_img_List.Count();
                    if (banner_img_count > 0)
                    {
                        for (int i = 0; i < banner_img_count; i++)
                        {
                            gw_goods_picture imgModel = new gw_goods_picture();
                            imgModel.goods_id = entity.id;
                            imgModel.type = 0;
                            imgModel.url = input.banner_img_List[i];
                            imgModel.sort = i + 1;
                            imgModel.is_default = false;
                            if (i == 0)//设为默认
                            {
                                imgModel.is_default = true;
                            }
                            banner_add.Add(imgModel);
                        }
                    }

                    if (info_img_count > 0)
                    {
                        for (int i = 0; i < info_img_count; i++)
                        {
                            gw_goods_picture imgModel = new gw_goods_picture();
                            imgModel.goods_id = entity.id;
                            imgModel.type = 1;
                            imgModel.url = input.info_img_List[i];
                            imgModel.sort = i + 1;
                            imgModel.is_default = false;
                            info_add.Add(imgModel);

                        }
                    }
                    if (banner_add.Count() > 0)
                    {
                        db.gw_goods_pictures.AddRange(banner_add);
                    }
                    if (info_add.Count() > 0)
                    {
                        db.gw_goods_pictures.AddRange(info_add);
                    }
                    var result = await db.SaveChangesAsync();
                    if (result > 0)
                    {
                        //return ReturnSuccess<int>(entity.id);
                        var msg = "0";
                        if (sale_price_is_change || settlement_price_is_change)
                        {
                            msg = "1";
                        }
                        LogHelper.WriteLog("管理员" + managerId + "修改：商品" + entity.id);
                        return new Response<int>() { code = 1, msg = msg, data = entity.id };
                    }
                    else
                    {
                        return ReturnError<int>("保存失败，请重试！");
                    }
                }
                return ReturnError<int>("商品不存在");
            }
            else
            {
                if (input.shop_id > 0)
                {
                    var entity = new gw_goods()
                    {
                        shop_id = input.shop_id,
                        category_id = input.category_id,
                        type_id = input.type_id,
                        name = input.name,
                        short_title = input.short_title,
                        weight = input.weight,
                        summary = input.summary == null ? "" : input.summary,
                        description = input.description == null ? "" : input.description,
                        limit_quantity = input.limit_quantity,
                        notify_admin_quantity = input.notify_admin_quantity,
                        category_id1 = input.category_id1,
                        category_id2 = input.category_id2,
                        remark = input.remark == null ? "" : input.remark,
                        update_time = DateTime.Now,
                        add_time = DateTime.Now,
                        deleted = false
                    };
                    if (input.freight_template_id > 0)
                    {
                        entity.freight_template_id = input.freight_template_id;
                    }
                    gw_goods_property _property = new gw_goods_property();
                    _property.settlement_price = input.settlement_price;
                    _property.sale_price = input.sale_price;
                    _property.market_price = input.market_price;
                    _property.service_rate = input.service_rate;
                    _property.stock_manage_type = 2;
                    _property.is_sale = true;
                    _property.published = 0;
                    _property.sort = input.sort;
                    _property.is_new = input.is_new;
                    _property.is_top = input.is_top;
                    entity.gw_goods_property = _property;
                    switch (entity.type_id)
                    {
                        case 1://拼手气
                            gw_goods_rule_group rule_group = new gw_goods_rule_group();
                            //rule_group.group_price = input.sale_price;
                            rule_group.red_packet = input.red_packet;
                            rule_group.require_num = input.require_num;
                            rule_group.duration = input.duration;
                            rule_group.start_time = input.start_time;
                            rule_group.is_sale = true;
                            rule_group.deleted = false;
                            rule_group.published = true;
                            if (input.end_time != null)
                            {
                                rule_group.end_time = input.end_time;
                            }
                            rule_group.add_time = DateTime.Now;
                            entity.gw_goods_rule_group = rule_group;
                            break;
                        case 2://合力免单
                            gw_goods_rule_free rule_free = new gw_goods_rule_free();
                            rule_free.require_num = input.require_num;
                            rule_free.duration = input.duration;
                            rule_free.start_time = input.start_time;
                            rule_free.is_sale = true;
                            rule_free.deleted = false;
                            rule_free.published = true;
                            if (input.end_time != null)
                            {
                                rule_free.end_time = input.end_time;
                            }
                            rule_free.add_time = DateTime.Now;
                            entity.gw_goods_rule_free = rule_free;
                            break;
                        case 4://1元购
                            gw_goods_rule_free rule_free_1 = new gw_goods_rule_free();
                            rule_free_1.require_num = input.require_num;
                            rule_free_1.duration = input.duration;
                            rule_free_1.start_time = input.start_time;
                            rule_free_1.is_sale = true;
                            rule_free_1.deleted = false;
                            rule_free_1.published = true;
                            if (input.end_time != null)
                            {
                                rule_free_1.end_time = input.end_time;
                            }
                            rule_free_1.add_time = DateTime.Now;
                            entity.gw_goods_rule_free = rule_free_1;
                            break;
                            //case 3://趣卡专享
                            //    break;
                    }
                    //商品服务
                    if (goods_service_list.Count > 0)
                    {

                        List<gw_goods_service> gsList = new List<gw_goods_service>();
                        gw_goods_service gs = new gw_goods_service();
                        foreach (var item in goods_service_list)
                        {
                            if (item > 0)
                            {
                                gs = db.gw_goods_services.FirstOrDefault(i => i.id == item);
                                if (gs != null)
                                {
                                    gsList.Add(gs);
                                }
                            }
                        }
                        entity.gw_goods_service = gsList;
                    }
                    //品牌
                    if (!string.IsNullOrEmpty(input.brand))
                    {
                        var brand = db.gw_base_brands.FirstOrDefault(i => i.name == input.brand);
                        if (brand != null)
                        {
                            entity.category_id3 = brand.id;
                        }
                        else
                        {
                            var gw_base_brand = new gw_base_brand();
                            gw_base_brand.name = input.brand;
                            gw_base_brand.logo = "";
                            gw_base_brand.status = 1;
                            gw_base_brand.add_time = DateTime.Now;
                            var brand_model = db.gw_base_brands.Add(gw_base_brand);
                            await db.SaveChangesAsync();
                            entity.category_id3 = brand_model.id;
                        }
                        if (!db.gw_shop_brand_mappings.Any(i => i.shop_id == entity.shop_id && i.brand_id == entity.category_id3 && i.category_id == entity.category_id2))
                        {
                            var shop_brand = new gw_shop_brand_mapping();
                            shop_brand.shop_id = entity.shop_id;
                            shop_brand.brand_id = entity.category_id3;
                            shop_brand.category_id = input.category_id2;
                            db.gw_shop_brand_mappings.Add(shop_brand);
                        }
                    }
                    var model = db.gw_goods.Add(entity);
                    await db.SaveChangesAsync();
                    //图片
                    //TODO：图片由临时文件夹转移到正式文件夹goods/shopId/goodsId
                    List<gw_goods_picture> banner_add = new List<gw_goods_picture>();
                    List<gw_goods_picture> info_add = new List<gw_goods_picture>();
                    var banner_img_count = input.banner_img_List == null ? 0 : input.banner_img_List.Count();
                    var info_img_count = input.info_img_List == null ? 0 : input.info_img_List.Count();
                    if (banner_img_count > 0)
                    {
                        for (int i = 0; i < banner_img_count; i++)
                        {
                            gw_goods_picture imgModel = new gw_goods_picture();
                            imgModel.goods_id = model.id;
                            imgModel.type = 0;
                            imgModel.url = input.banner_img_List[i];
                            imgModel.sort = i + 1;
                            imgModel.is_default = false;
                            if (i == 0)//设为默认
                            {
                                imgModel.is_default = true;
                            }
                            banner_add.Add(imgModel);
                        }
                    }
                    if (info_img_count > 0)
                    {
                        for (int i = 0; i < info_img_count; i++)
                        {
                            gw_goods_picture imgModel = new gw_goods_picture();
                            imgModel.goods_id = model.id;
                            imgModel.type = 1;
                            imgModel.url = input.info_img_List[i];
                            imgModel.sort = i + 1;
                            imgModel.is_default = false;
                            info_add.Add(imgModel);

                        }
                    }
                    if (banner_add.Count() > 0)
                    {
                        db.gw_goods_pictures.AddRange(banner_add);
                    }
                    if (info_add.Count() > 0)
                    {
                        db.gw_goods_pictures.AddRange(info_add);
                    }
                    //sku
                    var spec = db.gw_goods_specs.FirstOrDefault(i => i.name == "规格");
                    if (spec != null)
                    {
                        gw_goods_spec_value _spec = new gw_goods_spec_value
                        {
                            spec_id = spec.id,
                            goods_id = model.id,
                            name = "默认",
                            sort = 99,
                            thumb_url = input.banner_img_List.Count() > 0 ? input.banner_img_List[0] : "",
                            is_selected = true
                        };
                        var specModel = db.gw_goods_spec_values.Add(_spec);

                        gw_goods_sku _sku = new gw_goods_sku
                        {
                            goods_id = model.id,
                            specs = "[{\"spec_key\": \"规格\",\"spec_value\": \"默认\"}]",
                            service_rate = input.service_rate,
                            notify_admin_quantity = 10,
                            limit_quantity = 999,
                            all_stock = 1000,
                            stock_quantity = 1000,
                            published = true,
                            is_sale = true,
                            add_time = DateTime.Now,
                            market_price = new decimal?(input.market_price),
                            sale_price = new decimal?(input.sale_price),
                            settlement_price = input.settlement_price,
                            thumb_url = input.banner_img_List.Count() > 0 ? input.banner_img_List[0] : "",
                        };
                        _sku.gw_goods_spec_value.Add(specModel);
                        db.gw_goods_skus.Add(_sku);
                    }

                    var result = await db.SaveChangesAsync();
                    if (result > 0)
                    {
                        LogHelper.WriteLog("管理员" + managerId + "添加：商品" + model.id);
                        return ReturnSuccess<int>(model.id);
                    }
                    else
                    {
                        return ReturnError<int>("保存失败，请重试！");
                    }
                }
                else
                {
                    return ReturnError<int>("店铺不存在");
                }
            }
        }

        public IList<GoodsList> GetAllGoodsByPage(int iDisplayStart, int iDisplayLength, string dateMin, string dateMax, string title, string shopName, string code, string category, int categoryId, int shopId, int status, int type, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;
            var list = db.gw_goods
                .Include(i => i.gw_goods_property)
                .Include(i => i.gw_shop)
                .Include(i => i.gw_goods_picture)
                .Include(i => i.gw_goods_category)
                .Where(i => !i.deleted);
            if (type > 0)
            {
                list = list.Where(i => i.type_id == type);
            }
            if (!string.IsNullOrEmpty(code) || Validator.IsInt(code))
            {
                var goodsId = int.Parse(code);
                list = list.Where(m => m.id == goodsId);
            }
            if (shopId > -1)
            {
                list = list.Where(m => m.shop_id == shopId);
            }
            if (categoryId > -1)
            {
                list = list.Where(m => m.category_id == categoryId);
            }
            if (status > -1)
            {
                list = list.Where(m => m.gw_goods_property.published == status);
            }
            if (!string.IsNullOrWhiteSpace(title))
            {
                list = list.Where(m => m.name.Contains(title));
            }
            if (!string.IsNullOrWhiteSpace(shopName))
            {
                list = list.Where(m => m.gw_shop.name.Contains(shopName));
            }
            if (!string.IsNullOrEmpty(category))
            {
                list = list.Where(m => m.gw_goods_category.name.Contains(category));
            }
            if (!string.IsNullOrWhiteSpace(dateMin))
            {
                dtMin = DateTime.Parse(dateMin);
            }
            if (!string.IsNullOrWhiteSpace(dateMax))
            {
                dtMax = DateTime.Parse(dateMax).Date.AddDays(1); ;
            }
            list = list.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);
            totalCount = list.Count();
            list = list.OrderByDescending(m => m.add_time).Skip(iDisplayStart).Take(iDisplayLength);
            IList<GoodsList> dtos = new List<GoodsList>();
            foreach (var item in list)
            {
                GoodsList dto = new GoodsList();
                dto.ToGoodsList(item);
                dtos.Add(dto);
            }
            return dtos;
        }
        public IList<GoodsDto> GetGoodsByPage(int iDisplayStart, int iDisplayLength, string dateMin, string dateMax, string title, string shopName, string code, string category, int categoryId, int shopId, int status, int goodsType, int type, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            var list = db.gw_goods
                .Include(i => i.gw_goods_property)
                .Include(i => i.gw_goods_picture)
                .Include(i => i.gw_goods_sku)
                .Where(i => !i.deleted);
            if (type > -1)
            {
                switch (type)
                {
                    case 1://出售中
                        list = list.Where(i => i.gw_goods_property.published == 1 && i.gw_goods_property.is_sale && i.gw_goods_sku.Where(j => !j.deleted).Sum(j => j.stock_quantity) > 0);
                        break;
                    case 2://售罄
                        //list = list.Where(i => i.gw_goods_property.published == 1 && !i.gw_goods_property.is_sale);
                        list = list.Where(i => i.gw_goods_property.published == 1 && i.gw_goods_sku.Where(j => !j.deleted).Sum(j => j.stock_quantity) == 0);
                        break;
                    case 3://下架
                        list = list.Where(i => i.gw_goods_property.published == 0);
                        break;
                }
            }
            if (goodsType > 0)
            {
                list = list.Where(m => m.type_id == goodsType);
            }
            if (shopId > -1)
            {
                list = list.Where(m => m.shop_id == shopId);
            }
            if (!string.IsNullOrEmpty(code))
            {
                if (Validator.IsInt(code))
                {
                    var goodsId = int.Parse(code);
                    list = list.Where(m => m.id == goodsId);
                }
                else
                {
                    list = list.Where(m => m.name.Contains(code));
                }
            }
            totalCount = list.Count();
            list = list.OrderByDescending(m => m.add_time).Skip(iDisplayStart).Take(iDisplayLength);
            IList<GoodsDto> dtos = new List<GoodsDto>();
            foreach (var item in list)
            {
                GoodsDto dto = new GoodsDto();
                dto.ToGoodsDto(item);
                dtos.Add(dto);
            }
            return dtos;
        }

        public GoodsInput GetGoodsById(int id)
        {
            var entity = db.gw_goods
                 .Include(i => i.gw_goods_property)
                 .Include(i => i.gw_goods_rule_free)
                 .Include(i => i.gw_goods_rule_group)
                 .Include(i => i.gw_goods_service)
                 .Include(i => i.gw_base_brand)
                 .FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                GoodsInput dto = new GoodsInput();
                dto.ToGoodsInfo(entity);
                return dto;
            }
            else
            {
                return null;
            }
        }

        public bool SetGoodsIsNew(int manageId, int id, int isNew)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作商品{1}新品状态为{2}", manageId, id, isNew));
            var entity = db.gw_goods_propertys.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                entity.is_new = isNew == 1 ? true : false;
                db.SaveChanges();
                return true;
            }
            return false;
        }

        public bool SetGoodsIsTop(int manageId, int id, int isTop)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作商品{1}置顶状态为{2}", manageId, id, isTop));
            var entity = db.gw_goods_propertys.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                entity.is_top = isTop == 1 ? true : false;
                db.SaveChanges();
                return true;
            }
            return false;
        }

        public async Task<Response<bool>> SetGoodsIsUse(int manageId, int id, int isUse)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作商品{1}上架状态为{2}", manageId, id, isUse));
            var entity = db.gw_goods_propertys.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {

                if (isUse == 1)
                {

                    if (db.gw_goods_skus.Any(i => i.goods_id == id && !i.deleted))
                    {
                        entity.published = (byte)isUse;
                        entity.is_sale = true;
                        await db.SaveChangesAsync();
                        return ReturnSuccess<bool>(true);
                    }
                    else
                    {
                        return ReturnError<bool>("请先设置商品规格及SKU");
                    }
                }
                else
                {
                    entity.published = (byte)isUse;
                    await db.SaveChangesAsync();
                    return ReturnSuccess<bool>(true);
                }
            }
            return ReturnError<bool>("商品不存在");
        }
        #endregion

        public List<GoodsServiceDto> GetGoodsServiceList()
        {
            return db.gw_goods_services
                .Where(i => i.status == 1)
                .OrderBy(i => i.sort)
                .Select(item => new GoodsServiceDto
                {
                    id = item.id,
                    title = item.title
                }).ToList();
        }
        public async Task<int> ResetCategory(int goodsId = 0)
        {
            var list = db.gw_goods.Where(i => i.category_id != i.category_id2).OrderBy(i => i.id).Skip(0).Take(10);
            foreach (var item in list)
            {
                var parentCategory = db.gw_goods_categories.Where(i => i.id == item.category_id).Select(i => i.parent_id).FirstOrDefault();
                if (parentCategory > 0)
                {
                    item.category_id1 = (int)parentCategory;
                    item.category_id2 = item.category_id;
                }
            }
            var result = await db.SaveChangesAsync();
            return result;
        }
        #region 商品图片
        public List<GoodsPictureDto> GetGoodsPictures(int goodsId, int type)
        {
            var list = db.gw_goods_pictures
                .Where(i => i.goods_id == goodsId && i.type == type)
                .OrderBy(i => i.sort)
                .Select(item => new GoodsPictureDto
                {
                    id = item.id,
                    url = item.url
                });
            return list.ToList();
        }

        public async Task<Response<int>> AddorEditGoodsPictures(int managerId, GoodsPictureInput input)
        {
            if (input.good_id > 0)
            {
                var good = db.gw_goods
                     .Include(i => i.gw_goods_picture)
                     .FirstOrDefault(i => i.id == input.good_id);
                if (good != null)
                {
                    var delList = good.gw_goods_picture.Where(i => i.type == input.type_id);
                    if (delList.Count() > 0)
                    {
                        db.gw_goods_pictures.RemoveRange(delList);
                    }

                    List<gw_goods_picture> addList = new List<gw_goods_picture>();

                    var current_imglist_count = input.current_imglist == null ? 0 : input.current_imglist.Count();
                    var banner_img_count = input.banner_img_List == null ? 0 : input.banner_img_List.Count();
                    var info_img_count = input.info_img_List == null ? 0 : input.info_img_List.Count();

                    //if (current_imglist_count > 0)
                    //{
                    //    for (int i = 0; i < current_imglist_count; i++)
                    //    {
                    //        gw_goods_picture imgModel = new gw_goods_picture();
                    //        imgModel.good_id = input.good_id;
                    //        imgModel.type = (byte)input.type_id;
                    //        imgModel.url = input.current_imglist[i];
                    //        imgModel.sort = i + 1;
                    //        imgModel.is_default = false;
                    //        //if (i == 0)//设为默认
                    //        //{
                    //        //    imgModel.is_default = true;
                    //        //}
                    //        addList.Add(imgModel);
                    //    }
                    //}


                    if (banner_img_count > 0)
                    {
                        for (int i = 0; i < banner_img_count; i++)
                        {
                            gw_goods_picture imgModel = new gw_goods_picture();
                            imgModel.goods_id = input.good_id;
                            imgModel.type = 0;
                            imgModel.url = input.banner_img_List[i];
                            imgModel.sort = i + 1;
                            imgModel.is_default = false;
                            if (i == 0)//设为默认
                            {
                                imgModel.is_default = true;
                            }
                            addList.Add(imgModel);
                        }
                    }

                    if (info_img_count > 0)
                    {
                        for (int i = 0; i < info_img_count; i++)
                        {
                            gw_goods_picture imgModel = new gw_goods_picture();
                            imgModel.goods_id = input.good_id;
                            imgModel.type = 1;
                            imgModel.url = input.info_img_List[i];
                            imgModel.sort = i + 1;
                            imgModel.is_default = false;
                            //if (i == 0)//设为默认
                            //{
                            //    imgModel.is_default = true;
                            //}
                            addList.Add(imgModel);

                        }
                    }
                    if (addList.Count() > 0)
                    {
                        db.gw_goods_pictures.AddRange(addList);
                    }
                    var result = await db.SaveChangesAsync();
                    if (result > 0)
                    {
                        return ReturnSuccess<int>(result);
                    }
                    else
                    {
                        return ReturnError<int>("保存失败，请重试！");
                    }
                }
            }
            return ReturnError<int>("商品不存在，请重试！");
        }
        #endregion

        #region 商品规格
        public List<GoodsSpecDto> GetGoodsSpec(int goodsId)
        {
            var specList = db.gw_goods_spec_values
               .Where(i => i.goods_id == goodsId)
               .Select(i => i.spec_id).Distinct().ToList();
            var list = db.gw_goods_specs
               .Where(i => specList.Contains(i.id))
               .Select(item => new GoodsSpecDto
               {
                   id = item.id,
                   goods_id = goodsId,
                   name = item.name,
                   description = item.description
               }).ToList();

            return list;
        }

        public SpecWithValueDto GetSpecWithValue(int goodsId)
        {
            var imgSpecList = db.gw_goods_spec_values
                .Include(i => i.gw_goods_spec)
               .Where(i => i.goods_id == goodsId && i.thumb_url != "" && !i.deleted)
               .Select(item => new
               {
                   item.id,
                   item.name,
                   item.thumb_url,
                   item.spec_id,
                   spec_name = item.gw_goods_spec.name
               }).ToList();
            var textSpecList = db.gw_goods_spec_values
                .Include(i => i.gw_goods_spec)
               .Where(i => i.goods_id == goodsId && i.thumb_url == "" && !i.deleted)
               .Select(item => new
               {
                   item.id,
                   item.name,
                   item.thumb_url,
                   item.spec_id,
                   spec_name = item.gw_goods_spec.name
               }).ToList();
            var imgSpec = new SpecTypeDto() { };
            if (imgSpecList.Count() > 0)
            {
                imgSpec.id = imgSpecList[0].spec_id;
                imgSpec.name = imgSpecList[0].spec_name;
                imgSpec.value_list = imgSpecList.Select(item => new SingleSpecValueDto
                {
                    id = item.id,
                    name = item.name,
                    thumb_url = item.thumb_url
                }).ToList();
            }
            else
            {
                imgSpec = null;
            }
            var textSpec = new SpecTypeDto() { };
            if (textSpecList.Count() > 0)
            {
                textSpec.id = textSpecList[0].spec_id;
                textSpec.name = textSpecList[0].spec_name;
                textSpec.value_list = textSpecList.Select(item => new SingleSpecValueDto
                {
                    id = item.id,
                    name = item.name,
                    thumb_url = item.thumb_url
                }).ToList();
            }
            else
            {
                textSpec = null;
            }
            if (imgSpec == null && textSpec == null)
            {
                return null;
            }
            return new SpecWithValueDto() { img_spec = imgSpec, text_spec = textSpec };
        }

        public async Task<Response<int>> DeleteGoodsSpec(int managerId, int goodsId, int specId)
        {
            var skuList = db.gw_goods_skus.Include(i => i.gw_goods_spec_value).Where(i => i.goods_id == goodsId && i.gw_goods_spec_value.Where(s => s.spec_id == specId).Count() > 0);
            foreach (var item in skuList)
            {
                item.gw_goods_spec_value = null;
                item.deleted = true;
                item.is_sale = false;
                item.published = false;
                item.all_stock -= (int)item.stock_quantity;
                item.stock_quantity = 0;//TODO：加锁
            }
            var list = db.gw_goods_spec_values.Where(i => i.goods_id == goodsId && i.spec_id == specId);
            if (list != null && list.Count() > 0)
            {
                // db.gw_goods_spec_values.RemoveRange(list);
                foreach (var item in list)
                {
                    item.deleted = true;
                }
            }
            await db.SaveChangesAsync();
            if (!db.gw_goods_skus.Any(i => i.goods_id == goodsId && !i.deleted))
            {
                var goods = db.gw_goods_propertys.FirstOrDefault(i => i.id == goodsId);
                goods.published = 0;
                goods.is_sale = false;
                await db.SaveChangesAsync();
            }
            return ReturnSuccess<int>(1);
        }

        public List<gw_goods_spec> GetSpec()
        {
            return db.gw_goods_specs.ToList();
        }

        public async Task<Response<int>> AddGoodsSpec(int managerId, int goodsId, int specId)
        {
            if (goodsId > 0 && specId > 0)
            {
                var goodSpec = db.gw_goods_spec_values.FirstOrDefault(i => i.goods_id == goodsId && i.spec_id == specId);
                if (goodSpec != null)
                {
                    return ReturnError<int>("该规格已添加");
                }
                gw_goods_spec_value entity = new gw_goods_spec_value();
                entity.goods_id = goodsId;
                entity.spec_id = specId;
                entity.name = "";
                entity.sort = 99;
                entity.is_selected = false;
                var model = db.gw_goods_spec_values.Add(entity);
                var result = await db.SaveChangesAsync();
                if (result > 0)
                {
                    return ReturnSuccess<int>(model.id);
                }
                else
                {
                    return ReturnError<int>("保存失败，请重试！");
                }
            }
            return ReturnError<int>("参数错误！");

        }

        public async Task<Response<int>> AddGoodsSpec(int managerId, int goodsId, string name, string description)
        {
            if (goodsId > 0)
            {
                if (string.IsNullOrEmpty(name))
                {
                    return ReturnError<int>("请填写规格！");
                }

                gw_goods_spec spec = new gw_goods_spec();
                spec = db.gw_goods_specs.FirstOrDefault(i => name == i.name);
                if (spec == null)
                {
                    spec = new gw_goods_spec();
                    spec.name = name;
                    spec.description = description;
                    spec = db.gw_goods_specs.Add(spec);
                }
                var goodSpec = db.gw_goods_spec_values.FirstOrDefault(i => i.goods_id == goodsId && i.spec_id == spec.id);
                if (goodSpec != null)
                {
                    return ReturnError<int>("该规格已添加");
                }
                gw_goods_spec_value entity = new gw_goods_spec_value();
                entity.goods_id = goodsId;
                entity.spec_id = spec.id;
                entity.name = "";
                entity.sort = 99;
                entity.is_selected = false;
                var model = db.gw_goods_spec_values.Add(entity);
                var result = await db.SaveChangesAsync();
                if (result > 0)
                {
                    return ReturnSuccess<int>(model.id);
                }
                else
                {
                    return ReturnError<int>("保存失败，请重试！");
                }
            }
            return ReturnError<int>("参数错误！");
        }
        #endregion

        #region 商品规格值
        public List<GoodsSpecValueDto> GetGoodsSpecValue(int goodsId, int specId)
        {
            var list = from gs in db.gw_goods_spec_values
                       join g in db.gw_goods on gs.goods_id equals g.id
                       where gs.goods_id == goodsId && gs.spec_id == specId
                       select new GoodsSpecValueDto
                       {
                           id = gs.id,
                           goods_id = g.id,
                           goodsname = g.name,
                           name = gs.name,
                           sort = (int)gs.sort,
                           thumb_url = gs.thumb_url,
                           is_selected = (bool)gs.is_selected,
                       };
            return list.ToList();
        }

        public GoodsSpecValueInput GetGoodsSpecValueById(int id)
        {
            var model = db.gw_goods_spec_values
               .Where(i => i.id == id)
               .Select(item => new GoodsSpecValueInput
               {
                   id = item.id,
                   goods_id = item.goods_id,
                   spec_id = item.spec_id,
                   name = item.name,
                   sort = (int)item.sort,
                   thumb_url = item.thumb_url,
                   is_selected = (bool)item.is_selected,
               }).FirstOrDefault();
            return model;
        }

        public async Task<Response<int>> AddorEditGoodsSpecValue(int managerId, GoodsSpecValueInput input)
        {
            //TODO:数据验证
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(input.name))
            {
                errorList.Append("名称不能为空；</br>");
            }
            if (input.goods_id <= 0 && input.spec_id <= 0)
            {
                errorList.Append("数据参数错误；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<int>(errorList.ToString());
            }
            if (input.id > 0)
            {
                var model = db.gw_goods_spec_values
                     .Include(i => i.gw_goods_spec)
                     .FirstOrDefault(i => i.id == input.id);
                if (model != null)
                {
                    model.name = input.name;
                    model.thumb_url = input.thumb_url;
                    model.sort = input.sort;
                    model.is_selected = input.is_selected;
                    var result = await db.SaveChangesAsync();
                    if (result > 0)
                    {
                        return ReturnSuccess<int>(result);
                    }
                    else
                    {
                        return ReturnError<int>("保存失败，请重试！");
                    }
                }
                return ReturnError<int>("规格值不存在！");
            }
            else
            {
                gw_goods_spec_value entity = new gw_goods_spec_value();
                entity.name = input.name;
                entity.goods_id = input.goods_id;
                entity.spec_id = input.spec_id;
                entity.thumb_url = input.thumb_url;
                entity.sort = input.sort;
                entity.is_selected = input.is_selected;
                var model = db.gw_goods_spec_values.Add(entity);
                var result = await db.SaveChangesAsync();
                if (result > 0)
                {
                    return ReturnSuccess<int>(model.id);
                }
                else
                {
                    return ReturnError<int>("保存失败，请重试！");
                }
            }
        }

        public async Task<Response<int>> DeleteGoodsSpecValue(int id, int goods_id)
        {
            var model = db.gw_goods_spec_values.FirstOrDefault(i => i.id == id);
            if (model != null)
            {
                var sku_spec = db.gw_goods_skus
                         .Include(i => i.gw_goods_spec_value)
                         .Where(i => i.goods_id == goods_id && i.gw_goods_spec_value.Where(s => s.id == id).Count() > 0);
                foreach (var item in sku_spec.ToList())
                {
                    item.gw_goods_spec_value = null;
                    item.deleted = true;
                    item.is_sale = false;
                    item.published = false;
                    item.all_stock -= (int)item.stock_quantity;
                    item.stock_quantity = 0;//TODO：加锁
                }
                ////await db.SaveChangesAsync();
                //db.gw_goods_spec_values.Remove(model);
                model.deleted = true;
                await db.SaveChangesAsync();
                if (!db.gw_goods_skus.Any(i => i.goods_id == goods_id && !i.deleted))
                {
                    var goods = db.gw_goods_propertys.FirstOrDefault(i => i.id == goods_id);
                    goods.published = 0;
                    goods.is_sale = false;
                    await db.SaveChangesAsync();
                }
                return ReturnSuccess<int>(1);
            }
            else
            {
                return ReturnError<int>("操作失败，请重试！");
            }
        }
        #endregion

        #region 商品SKU
        public async Task<Response<int>> MakeSku(int goodsId)
        {
            var model = db.gw_goods_propertys.FirstOrDefault(i => i.id == goodsId);
            if (model == null)
            {
                return ReturnError<int>("商品信息异常！");
            }
            //spec_value_list 规格列表（规格包含规格类型）
            var spec_value_list = db.gw_goods_spec_values
                .Include(i => i.gw_goods_spec)
                .Where(i => i.goods_id == goodsId && i.is_selected == true && !i.deleted && i.name != null)
                .OrderByDescending(i => i.sort)
                .Select(item => new
                {
                    id = item.id,
                    //goods_id = item.goods_id,
                    name = item.name,
                    thumb_url = item.thumb_url,
                    spec_id = item.gw_goods_spec.id,
                    spec_name = item.gw_goods_spec.name,
                    //spec_description = item.gw_goods_spec.description
                }).ToList();

            if (spec_value_list.Count() <= 0)
            {
                return ReturnError<int>("请先设置规格！");
            }
            else
            {
                //specCount 规格类型数量
                var specList = (from p in spec_value_list select p.spec_id).Distinct().ToList();
                var specCount = specList.Count();
                if (specCount <= 0)
                {
                    return ReturnError<int>("生成失败，请先设置规格！");
                }
                else
                {
                    //无图规格
                    var val_list_text = spec_value_list.Where(i => i.thumb_url == "").ToList();
                    //有图规格
                    var val_list_img = spec_value_list.Where(i => i.thumb_url != "").ToList();
                    if (spec_value_list.Count() != (val_list_img.Count() + val_list_text.Count()))
                    {
                        return ReturnError<int>("规格信息异常，请重新设置规格！");
                    }
                    //skuList 当前所有SKU
                    var skuList = db.gw_goods_skus.Include(i => i.gw_goods_spec_value).Where(i => i.goods_id == goodsId && !i.deleted).ToList();
                    foreach (var item in skuList)
                    {
                        item.gw_goods_spec_value = null;
                        item.deleted = true;
                        item.is_sale = false;
                        item.published = false;
                        item.all_stock -= (int)item.stock_quantity;
                        item.stock_quantity = 0;
                    }

                    //var delskuList = db.gw_goods_skus.Include(i => i.gw_goods_spec_value).Where(i => i.goods_id == goodsId && i.deleted).ToList();
                    //foreach (var item in delskuList)
                    //{
                    //    item.gw_goods_spec_value = null;
                    //    item.deleted = true;
                    //    item.is_sale = false;
                    //    item.published = false;
                    //    item.all_stock -= (int)item.stock_quantity;
                    //    item.stock_quantity = 0;
                    //}
                    //var delSkuList = skuList.Where(i => i.gw_goods_spec_value.Count(s => specList.Contains(s.spec_id)) != specCount).ToList();
                    //var exitSkuList = skuList.Where(i => i.gw_goods_spec_value.Count(s => specList.Contains(s.spec_id)) == specCount).ToList();
                    //foreach (var item in delSkuList)
                    //{
                    //    item.gw_goods_spec_value = null;
                    //    item.deleted = true;
                    //    item.is_sale = false;
                    //    item.published = false;
                    //    item.all_stock -= (int)item.stock_quantity;
                    //    item.stock_quantity = 0;
                    //}
                    //foreach (var item in exitSkuList)
                    //{
                    //    item.gw_goods_spec_value = null;
                    //}
                    ////db.gw_goods_skus.RemoveRange(skuList);
                    await db.SaveChangesAsync();
                    ////下架自动生成的SKU TODO:加锁
                    //var del_sku = skuList.Where(i=>i.gw_goods_spec_value.Count(s=>s.name=="默认")>0).ToList();
                    //foreach (var item in del_sku)
                    //{
                    //    //item.gw_goods_spec_value = null;
                    //    item.deleted = true;
                    //    item.is_sale = false;
                    //    item.published = false;
                    //    item.all_stock -=(int)item.stock_quantity;
                    //    item.stock_quantity = 0;
                    //}
                    foreach (var img in val_list_img)
                    {
                        List<int> spec_ids = new List<int>();



                        if (val_list_text.Count > 0)
                        {
                            var text_spec_str = "";
                            foreach (var text in val_list_text)
                            {
                                gw_goods_sku _sku = new gw_goods_sku
                                {
                                    goods_id = goodsId,
                                    service_rate = model.service_rate,
                                    notify_admin_quantity = 10,
                                    limit_quantity = 999,
                                    all_stock = 1000,
                                    stock_quantity = 1000,
                                    published = true,
                                    is_sale = true,
                                    add_time = DateTime.Now,
                                    market_price = new decimal?(model.market_price),
                                    sale_price = new decimal?(model.sale_price),
                                    settlement_price = model.settlement_price,
                                    thumb_url = img.thumb_url,
                                };
                                spec_ids.Add(text.id);
                                text_spec_str = "{\"spec_key\": \"" + text.spec_name + "\",\"spec_value\": \"" + text.name + "\"},";
                                var textModel = db.gw_goods_spec_values.FirstOrDefault(i => i.id == text.id);

                                _sku.specs = "[" + text_spec_str + "{\"spec_key\": \"" + img.spec_name + "\",\"spec_value\": \"" + img.name + "\"}]";
                                //修改已存在的SKU TODO:加锁
                                spec_ids.Add(img.id);
                                if (textModel != null)
                                {
                                    _sku.gw_goods_spec_value.Add(textModel);
                                }
                                var imgModel = db.gw_goods_spec_values.FirstOrDefault(i => i.id == img.id);
                                if (imgModel != null)
                                {
                                    _sku.gw_goods_spec_value.Add(imgModel);
                                }
                                db.gw_goods_skus.Add(_sku);
                                await db.SaveChangesAsync();

                                //var spec_ids_count = spec_ids.Count();
                                //var exit_sku = exitSkuList.Where(i => i.gw_goods_spec_value.Count(s => spec_ids.Contains(s.id)) == spec_ids_count).ToList();
                                //if (exit_sku.Count() == 0)
                                //{
                                //    //_sku.gw_goods_spec_value = null;
                                //    //添加不存在的新SKU
                                //    if (textModel != null)
                                //    {
                                //        _sku.gw_goods_spec_value.Add(textModel);
                                //    }
                                //    var imgModel = db.gw_goods_spec_values.FirstOrDefault(i => i.id == img.id);
                                //    if (imgModel != null)
                                //    {
                                //        _sku.gw_goods_spec_value.Add(imgModel);
                                //    }
                                //    db.gw_goods_skus.Add(_sku);
                                //    await db.SaveChangesAsync();

                                //}
                                //else
                                //{
                                //    if (textModel != null)
                                //    {
                                //        exit_sku[0].gw_goods_spec_value.Add(textModel);
                                //    }
                                //    var imgModel = db.gw_goods_spec_values.FirstOrDefault(i => i.id == img.id);
                                //    if (imgModel != null)
                                //    {
                                //        exit_sku[0].gw_goods_spec_value.Add(imgModel);
                                //    }
                                //    //exit_sku.market_price = new decimal?(model.market_price);
                                //    //exit_sku.sale_price = new decimal?(model.sale_price);
                                //    //exit_sku.service_rate = model.service_rate;
                                //    exit_sku[0].thumb_url = img.thumb_url;
                                //    exit_sku[0].specs = _sku.specs;
                                //    exit_sku[0].published = true;
                                //    exit_sku[0].is_sale = true;
                                //    exit_sku[0].deleted = false;
                                //}
                                spec_ids.Remove(text.id);
                                spec_ids.Remove(img.id);
                            }
                        }
                        else
                        {
                            gw_goods_sku _sku = new gw_goods_sku
                            {
                                goods_id = goodsId,
                                service_rate = model.service_rate,
                                notify_admin_quantity = 10,
                                limit_quantity = 999,
                                all_stock = 1000,
                                stock_quantity = 1000,
                                published = true,
                                is_sale = true,
                                add_time = DateTime.Now,
                                market_price = new decimal?(model.market_price),
                                sale_price = new decimal?(model.sale_price),
                                settlement_price = model.settlement_price,
                                thumb_url = img.thumb_url,
                            };
                            var imgModel = db.gw_goods_spec_values.FirstOrDefault(i => i.id == img.id);
                            if (imgModel != null)
                            {
                                _sku.gw_goods_spec_value.Add(imgModel);
                            }
                            //_sku.specs = "[" + text_spec_str + "{\"spec_key\": \"" + img.spec_name + "\",\"spec_value\": \"" + img.name + "\"}]";
                            _sku.specs = "[{\"spec_key\": \"" + img.spec_name + "\",\"spec_value\": \"" + img.name + "\"}]";

                            //修改已存在的SKU TODO:加锁
                            spec_ids.Add(img.id);
                            db.gw_goods_skus.Add(_sku);
                            await db.SaveChangesAsync();
                            // var spec_ids_count = spec_ids.Count();
                            //var exit_sku = exitSkuList.FirstOrDefault(i => i.gw_goods_spec_value.Count(s => spec_ids.Contains(s.id)) == spec_ids_count);
                            //if (exit_sku == null)
                            //{
                            //    //添加不存在的新SKU
                            //    db.gw_goods_skus.Add(_sku);
                            //    await db.SaveChangesAsync();
                            //}
                            //else
                            //{
                            //    if (imgModel != null)
                            //    {
                            //        exit_sku.gw_goods_spec_value.Add(imgModel);
                            //    }
                            //    exit_sku.thumb_url = img.thumb_url;
                            //    exit_sku.specs = _sku.specs;
                            //    exit_sku.published = true;
                            //    exit_sku.is_sale = true;
                            //    exit_sku.deleted = false;
                            //}
                            spec_ids.Remove(img.id);
                        }

                    }
                    //var result = await db.SaveChangesAsync();
                    //if (result > 0)
                    //{
                    return ReturnSuccess<int>(1);
                    //}
                    //else
                    //{
                    //    return ReturnError<int>("生成失败，请重试！");
                    //}
                }
            }
        }
        public List<GoodsSkuDto> GetGoodsSkuList(int goodsId)
        {
            var sku = db.gw_goods_skus
                     .Include(i => i.gw_goods_spec_value)
                     .Where(i => i.goods_id == goodsId && !i.deleted);

            var list = from gs in db.gw_goods_skus
                       join g in db.gw_goods on gs.goods_id equals g.id
                       where gs.goods_id == goodsId && !gs.deleted
                       select new GoodsSkuDto
                       {
                           id = gs.id,
                           goodsname = g.name,
                           thumb_url = gs.thumb_url,
                           market_price = (decimal)gs.market_price,
                           sale_price = (decimal)gs.sale_price,
                           service_rate = (decimal)gs.service_rate,
                           all_stock = gs.all_stock,
                           stock_quantity = (int)gs.stock_quantity,
                           published = gs.published,
                           specs = gs.specs
                       };
            return list.ToList();
        }
        public GoodsSkuDto GetGoodsSkueById(int id)
        {
            var model = from gs in db.gw_goods_skus
                        join g in db.gw_goods on gs.goods_id equals g.id
                        where gs.id == id
                        select new GoodsSkuDto
                        {
                            id = gs.id,
                            goodsname = g.name,
                            market_price = (decimal)gs.market_price,
                            sale_price = (decimal)gs.sale_price,
                            service_rate = (decimal)gs.service_rate,
                            all_stock = gs.all_stock,
                            stock_quantity = (int)gs.stock_quantity,
                            published = gs.published,
                            specs = gs.specs
                        };
            return model.FirstOrDefault();
        }
        public IList<GoodsSkuDto> GetGoodsSkuListByPage(int iDisplayStart, int iDisplayLength, int goodsId, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            var list = from gs in db.gw_goods_skus
                       join g in db.gw_goods on gs.goods_id equals g.id
                       where gs.goods_id == goodsId && !gs.deleted
                       select new GoodsSkuDto
                       {
                           id = gs.id,
                           goodsname = g.name,
                           market_price = (decimal)gs.market_price,
                           sale_price = (decimal)gs.sale_price,
                           service_rate = (decimal)gs.service_rate,
                           all_stock = gs.all_stock,
                           stock_quantity = (int)gs.stock_quantity,
                           published = gs.published,
                           specs = gs.specs
                       };
            totalCount = list.Count();
            list = list.OrderByDescending(m => m.id).Skip(iDisplayStart - 1).Take(iDisplayLength);
            return list.ToList();
        }
        public SpecSkuDto GetGoodsSpecBySkuCount(int goodsId)
        {
            //所有规格及其数量
            var specValAll = db.gw_goods_spec_values
               .Where(i => i.goods_id == goodsId && !i.deleted)
               .GroupBy(i => i.spec_id)
               .Select(item => new
               { id = item.Key, count = item.Count() }).ToList();
            //SKU规格值
            var specValueList = db.gw_goods_spec_values
                .Include(i => i.gw_goods_sku)
                .Include(i => i.gw_goods_spec)
               .Where(i => i.goods_id == goodsId && !i.deleted && i.gw_goods_sku.Count(j => !j.deleted) > 0).ToList();
            if (specValueList.Count() > 0)
            {
                //SKU规格及其数量
                var specList0 = specValueList
                .GroupBy(i => i.spec_id)
               .Select(item => new
               { id = item.Key, count = item.Count() }).ToList();
                var specArr = from s in specList0
                              join all in specValAll on s.id equals all.id
                              select new { id = s.id, count = s.count, total = all.count };
                var specList1 = from s in specArr
                                join sv in db.gw_goods_specs on s.id equals sv.id
                                orderby s.count descending
                                orderby s.total ascending
                                select new GoodsSpecDto { id = s.id, name = sv.name };
                var specList = specList1.ToList();
                var specId0 = specList[0].id;

                if (specList.Count() == 1)
                {
                    var skuDtoList = db.gw_goods_skus
                        //.Include(i=>i.gw_goods)
                        .Include(i => i.gw_goods_spec_value)
                        .Where(i => i.goods_id == goodsId && !i.deleted && i.gw_goods_spec_value.Where(j => j.spec_id == specId0).Count() > 0)
                        .Select(item => new GoodsSkuDto
                        {
                            id = item.id,
                            //goods_type=item.gw_goods.type_id,
                            market_price = item.market_price == null ? 0 : (decimal)item.market_price,
                            sale_price = item.sale_price == null ? 0 : (decimal)item.sale_price,
                            settlement_price = item.settlement_price == null ? 0 : (decimal)item.settlement_price,
                            service_rate = item.service_rate == null ? 0 : (decimal)item.service_rate,
                            all_stock = item.all_stock,
                            stock_quantity = item.stock_quantity == null ? 0 : (int)item.stock_quantity,
                            specs = item.gw_goods_spec_value.FirstOrDefault(j => j.spec_id == specId0).name
                        });
                    var sku = skuDtoList.ToList();
                    return new SpecSkuDto { goods_spec = specList, goods_specvalue = null, goods_sku = sku };
                }
                else if (specList.Count() == 2)
                {
                    //var specId1 = specList[1].id;
                    //var skuDtoList1 = db.gw_goods_skus
                    //   .Include(i => i.gw_goods_spec_value)
                    //   .Where(i => i.goods_id == goodsId && !i.deleted)
                    //   .Select(item => new GoodsSkuDto
                    //   {
                    //       id = item.id,
                    //       sale_price = item.sale_price == null ? 0 : (decimal)item.sale_price,
                    //       all_stock = item.all_stock,
                    //       stock_quantity = item.stock_quantity == null ? 0 : (int)item.stock_quantity,
                    //       market_price = item.market_price == null ? 0 : (decimal)item.market_price,
                    //       specs = item.gw_goods_spec_value.FirstOrDefault(j => j.spec_id == specId1).name
                    //   });
                    //var sku = skuDtoList1.ToList();
                    var specValList = db.gw_goods_spec_values
                     .Include(i => i.gw_goods_sku)
                     .Include(i => i.gw_goods_spec)
                    .Where(i => i.goods_id == goodsId && !i.deleted && i.spec_id == specId0 && i.gw_goods_sku.Count(j => !j.deleted) > 0)
                    .Select(item => new GoodsSpecValueDto
                    {
                        id = item.id,
                        name = item.name,
                        sku_count = item.gw_goods_sku.Where(j => !j.deleted).GroupBy(j => j.id).Select(k => k.Key).Count(),
                        sku = item.gw_goods_sku.Where(j => !j.deleted).Select(s => new GoodsSkuDto
                        {
                            id = s.id,
                            //goods_type = s.gw_goods.type_id,
                            market_price = s.market_price == null ? 0 : (decimal)s.market_price,
                            sale_price = s.sale_price == null ? 0 : (decimal)s.sale_price,
                            settlement_price = s.settlement_price == null ? 0 : (decimal)s.settlement_price,
                            service_rate = s.service_rate == null ? 0 : (decimal)s.service_rate,
                            all_stock = s.all_stock,
                            stock_quantity = s.stock_quantity == null ? 0 : (int)s.stock_quantity,
                            specs = s.specs,
                            //published=s.published,
                            //is_sale = s.is_sale,
                            //thumb_url=s.thumb_url
                        }).ToList(),
                    }).ToList();
                    return new SpecSkuDto { goods_spec = specList, goods_specvalue = specValList, goods_sku = null };
                }

            }
            return null;
        }
        public async Task<Response<int>> EditGoodsSku(int managerId, GoodsSkuInput input)
        {
            //TODO: 数据验证
            StringBuilder errorList = new StringBuilder();
            if (input.stock_quantity < 0)
            {
                errorList.Append("库存不能小于0；</br>");
            }
            if (input.sale_price < 0)
            {
                errorList.Append("平台价不能小于0；</br>");
            }
            //if (input.service_rate < 0)
            //{
            //    errorList.Append("服务费率不能小于0；</br>");
            //}
            if (input.settlement_price < 0)
            {
                errorList.Append("结算价不能小于0；</br>");
            }
            if (input.market_price < 0)
            {
                errorList.Append("市场价不能小于0；</br>");
            }
            if (input.market_price < input.sale_price)
            {
                errorList.Append("平台价不能大于市场价；</br>");
            }
            if (input.sale_price < input.settlement_price)
            {
                errorList.Append("结算价不能大于平台价；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<int>(errorList.ToString());
            }
            if (input.id > 0)
            {
                //TODO: 加锁
                var model = db.gw_goods_skus
                    .Include(i => i.gw_goods)
                    .Include(i => i.gw_goods.gw_goods_property)
                     .FirstOrDefault(i => i.id == input.id);
                if (model != null)
                {
                    model.market_price = input.market_price;
                    model.sale_price = input.sale_price;
                    //model.service_rate = input.service_rate;
                    model.settlement_price = input.settlement_price;
                    model.thumb_url = input.thumb_url == null ? model.thumb_url : input.thumb_url;
                    var stocknumber = input.stock_quantity - model.stock_quantity;
                    model.all_stock += (int)stocknumber;
                    model.stock_quantity = input.stock_quantity;
                    model.is_sale = model.stock_quantity == 0 ? false : true;
                    await db.SaveChangesAsync();
                    var min_sale_price = db.gw_goods_skus.Where(i => i.goods_id == model.goods_id && !i.deleted).Min(i => i.sale_price);
                    var min_market_price = db.gw_goods_skus.Where(i => i.goods_id == model.goods_id && !i.deleted).Min(i => i.market_price);
                    if (model.gw_goods.gw_goods_property.sale_price != min_sale_price)
                    {
                        model.gw_goods.gw_goods_property.sale_price = (decimal)min_sale_price;
                    }
                    if (model.gw_goods.gw_goods_property.market_price != min_market_price)
                    {
                        model.gw_goods.gw_goods_property.market_price = (decimal)min_market_price;
                    }
                    await db.SaveChangesAsync();
                    return ReturnSuccess<int>(model.all_stock);
                }
            }
            return ReturnError<int>("该商品SKU不存在！");
        }
        public async Task<Response<int>> DeleteSku(int id)
        {
            var model = db.gw_goods_skus.FirstOrDefault(i => i.id == id);
            var skuNum = db.gw_goods_skus.Where(i => i.goods_id == model.goods_id && !i.deleted).Count();
            if (model != null)
            {
                if (skuNum > 1)
                {
                    model.deleted = true;
                    model.published = false;
                    model.is_sale = false;
                    model.all_stock -= (int)model.stock_quantity;
                    model.stock_quantity = 0;//TODO：加锁
                    //model.gw_goods_spec_value = null;
                    await db.SaveChangesAsync();
                    return ReturnSuccess<int>(model.id);
                }
                else
                {
                    return ReturnError<int>("必须设置至少一个SKU");
                }
            }
            else
            {
                return ReturnError<int>("操作失败，请重试");
            }
            //var goods = db.gw_goods.Include(i => i.gw_goods_sku).FirstOrDefault(i=>i.id== id);
            //var skulist = db.gw_goods_skus.Include(i => i.gw_goods_spec_value).Where(i => i.goods_id == id);
            //foreach (var item in skulist)
            //{
            //    item.gw_goods_spec_value = null;
            //}
            //List<gw_goods_sku> s = new List<gw_goods_sku>();
            //foreach (var item in goods.gw_goods_sku)
            //{
            //    s.Add(item);
            //}
            // db.gw_goods_skus.RemoveRange(s);
        }
        public bool SetGoodsSkuIsUse(int manageId, int id, int isUse)
        {
            var entity = db.gw_goods_skus.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                entity.published = isUse == 1 ? true : false;
                if (isUse == 1)
                {
                    entity.is_sale = true;
                }
                db.SaveChanges();
                return true;
            }
            return false;
        }

        public async Task<Response<int>> BulkUpdateSku(int managerId, int id, string numberStr, int type)
        {
            StringBuilder errorList = new StringBuilder();
            if (id <= 0)
            {
                errorList.Append("商品参数错误；</br>");
            }
            if (string.IsNullOrEmpty(numberStr) || !Validator.IsDecimal(numberStr))
            {
                if (type == 1)
                {
                    errorList.Append("请输入有效价格；</br>");
                }
                else if (type == 2)
                {
                    errorList.Append("请输入有效库存；</br>");
                }
                else if (type == 4)
                {
                    errorList.Append("请输入有效库存；</br>");
                }
                else if (type == 3)
                {
                    errorList.Append("请输入有效库存；</br>");
                }
                else
                {
                    errorList.Append("输入信息有误；</br>");
                }
            }
            decimal number = decimal.Parse(numberStr);
            if (number < 0)
            {
                errorList.Append("输入数据不能小于0；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<int>(errorList.ToString());
            }
            if (id > 0)
            {
                //TODO: 加锁
                var list = db.gw_goods_skus
                     .Where(i => i.goods_id == id && !i.deleted);
                foreach (var item in list)
                {
                    if (type == 1)//价格
                    {
                        item.sale_price = number;
                    }
                    else if (type == 2)//改库存
                    {
                        var stocknumber = (int)number - item.stock_quantity;
                        item.all_stock += (int)stocknumber;
                        item.stock_quantity = (int)number;
                        item.is_sale = item.stock_quantity == 0 ? false : true;
                    }
                    else if (type == 3)//加库存
                    {
                        item.all_stock += (int)number;
                        item.stock_quantity += (int)number;
                        item.is_sale = item.stock_quantity == 0 ? false : true;
                    }
                }
                var result = await db.SaveChangesAsync();
                if (type == 1)
                {
                    var minPrice = db.gw_goods_skus.Where(i => i.goods_id == id && !i.deleted).Min(i => i.sale_price);
                    var goods = db.gw_goods_propertys.FirstOrDefault(i => i.id == id);
                    if (goods.sale_price != minPrice)
                    {
                        goods.sale_price = (decimal)minPrice;
                    }
                    await db.SaveChangesAsync();
                }
                return ReturnSuccess<int>(result);
            }
            return ReturnError<int>("该商品不存在！");
        }
        #endregion

        #region 商品类别
        public IList<CategoryDto> GetAllCategoryByPage(int iDisplayStart, int iDisplayLength, string dateMin, string dateMax, string title, int parentId, int type, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            var list = from c in db.gw_goods_categories
                       join p in db.gw_goods_categories.DefaultIfEmpty() on c.parent_id equals p.id
                       into l
                       from lgu in l.DefaultIfEmpty()
                       where c.parent_id == parentId && c.status > 0
                       select new CategoryDto
                       {
                           id = c.id,
                           parent_id = (int)c.parent_id,
                           parent_name = lgu.name,
                           type = c.type,
                           name = c.name,
                           icon = c.icon,
                           sort = c.sort,
                           layer = c.layer,
                           status = c.status,
                           service_rate = c.service_rate
                       };

            if (type > 0)
            {
                list = list.Where(m => m.type == type);
            }
            totalCount = list.Count();
            list = list.OrderBy(m => m.sort).Skip(iDisplayStart).Take(iDisplayLength);
            return list.ToList();
        }
        public CategoryInput GetCategoryById(int id)
        {
            var model = db.gw_goods_categories.Where(i => i.id == id)
                .Select(item => new CategoryInput
                {
                    id = id,
                    parent_id = (int)item.parent_id,
                    type = item.type,
                    name = item.name,
                    icon = item.icon,
                    sort = item.sort,
                    remark = item.remark,
                    status = item.status == 1 ? true : false,
                    service_rate = item.service_rate
                }).FirstOrDefault();
            return model;
        }
        public async Task<Response<int>> AddorEditCategory(int manageId, CategoryInput input)
        {
            //TODO:数据验证
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(input.name))
            {
                errorList.Append("名称不能为空；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<int>(errorList.ToString());
            }
            if (input.id > 0)
            {
                var model = db.gw_goods_categories
                     .FirstOrDefault(i => i.id == input.id);
                if (model != null)
                {
                    model.name = input.name;
                    model.icon = input.icon == null ? "" : input.icon;
                    model.sort = input.sort;
                    model.service_rate = input.service_rate;
                    model.status = (byte)(input.status ? 1 : 2);
                    var result = await db.SaveChangesAsync();
                    if (result > 0)
                    {
                        return ReturnSuccess<int>(model.id);
                    }
                    else
                    {
                        return ReturnError<int>("保存失败，请重试！");
                    }
                }
                return ReturnError<int>("规格值不存在！");
            }
            else
            {

                gw_goods_category entity = new gw_goods_category();
                entity.layer = 1;
                if (input.parent_id > 0)
                {
                    var parent = db.gw_goods_categories.FirstOrDefault(i => i.id == input.parent_id);
                    if (parent != null)
                    {
                        entity.layer = (byte)((int)parent.layer + 1);
                    }
                }
                entity.name = input.name;
                entity.parent_id = input.parent_id;
                entity.type = input.type;
                entity.icon = input.icon == null ? "" : input.icon;
                entity.service_rate = input.service_rate;
                entity.sort = input.sort;
                entity.status = (byte)(input.status ? 1 : 2);
                entity.remark = input.remark;
                entity.add_time = DateTime.Now;
                var model = db.gw_goods_categories.Add(entity);
                var result = await db.SaveChangesAsync();
                if (result > 0)
                {
                    return ReturnSuccess<int>(model.id);
                }
                else
                {
                    return ReturnError<int>("保存失败，请重试！");
                }
            }
        }
        public bool SetCategoryIsUse(int manageId, int id, int isUse)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作商品分类{1}状态为{2}", manageId, id, isUse));
            var entity = db.gw_goods_categories.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                entity.status = (byte)isUse;
                db.SaveChanges();
                return true;
            }
            return false;
        }
        public List<CategoryTreeDto> GetCategoryTree(int tid)
        {
            var categories = db.gw_goods_categories
                .Where(i => i.status > 0 && i.type == tid)
                .OrderBy(i => i.sort)
                .Select(c => new CategoryTreeDto
                {
                    id = c.id.ToString(),
                    pId = (c.parent_id == null || c.parent_id == 0) ? "" : c.parent_id.ToString(),
                    name = c.name,
                }).ToList();

            return categories;
        }
        #endregion

        public async Task<Response<int>> AddSpecValue(int managerId, int goodsId, int specId, string name, string img)
        {
            //TODO:数据验证
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(name))
            {
                errorList.Append("规格值不能为空；</br>");
            }
            if (goodsId <= 0 || specId <= 0)
            {
                errorList.Append("数据参数错误；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<int>(errorList.ToString());
            }
            var SpecValue = db.gw_goods_spec_values.FirstOrDefault(i => i.goods_id == goodsId && i.spec_id == specId && i.name == name);
            if (SpecValue == null)
            {
                gw_goods_spec_value entity = new gw_goods_spec_value();
                entity.name = name;
                entity.goods_id = goodsId;
                entity.spec_id = specId;
                entity.thumb_url = string.IsNullOrEmpty(img) ? "" : img;
                entity.sort = string.IsNullOrEmpty(img) ? 88 : 99;
                entity.is_selected = true;
                entity.deleted = false;
                var model = db.gw_goods_spec_values.Add(entity);
                var result = await db.SaveChangesAsync();
                return ReturnSuccess<int>(model.id);
            }
            else
            {
                SpecValue.thumb_url = string.IsNullOrEmpty(img) ? SpecValue.thumb_url : img;
                SpecValue.deleted = false;
                SpecValue.is_selected = true;
                await db.SaveChangesAsync();
                return ReturnSuccess<int>(SpecValue.id);
            }

        }
        public async Task<Response<int>> AddSpec(int managerId, int goodsId, string name, string description)
        {
            if (goodsId > 0)
            {
                if (string.IsNullOrEmpty(name))
                {
                    return ReturnError<int>("请填写规格！");
                }

                gw_goods_spec spec = new gw_goods_spec();
                spec = db.gw_goods_specs.FirstOrDefault(i => name == i.name);
                if (spec == null)
                {
                    spec = new gw_goods_spec();
                    spec.name = name;
                    spec.description = description;
                    spec = db.gw_goods_specs.Add(spec);
                }
                await db.SaveChangesAsync();
                return ReturnSuccess<int>(spec.id);
            }
            return ReturnError<int>("参数错误！");
        }

        public int GoodsSkuCount(int id)
        {
            return db.gw_goods_skus.Where(i => i.goods_id == id && !i.deleted).Count();
        }
        public int GetGoodsType(int id)
        {
            var model = db.gw_goods.FirstOrDefault(i => i.id == id);
            return model == null ? 1 : model.type_id;
        }

        public IList<CommentDto> GetAllCommentByPage(int iDisplayStart, int iDisplayLength, string dateMin, string dateMax, int status, out int totalCount, int? shopId = -1)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;
            var list = db.gw_goods_comments
                .Where(u => !u.deleted)
                .Select(item => new CommentDto
                {
                    id = item.id,
                    order_goods_id = item.order_goods_id,
                    goods_id = item.goods_id,
                    user_id = item.user_id,
                    sort = item.sort,
                    is_anonymity = item.is_anonymity == null ? false : (bool)item.is_anonymity,
                    nick_name = item.nick_name,
                    description_mark = item.description_mark,
                    attitude_mark = item.attitude_mark,
                    logistics_mark = item.logistics_mark,
                    review = item.review,
                    reply = item.reply,
                    yes_total = item.yes_total,
                    no_total = item.no_total,
                    status = item.status,
                    add_time = item.add_time
                });
            if (shopId != -1)
            {
                list = from c in list
                       join g in db.gw_goods on c.goods_id equals g.id
                       where g.shop_id == shopId
                       select c;
            }
            if (status > -1)
            {
                list = list.Where(m => m.status == status);
            }

            if (!string.IsNullOrWhiteSpace(dateMin))
            {
                dtMin = DateTime.Parse(dateMin);
            }
            if (!string.IsNullOrWhiteSpace(dateMax))
            {
                dtMax = DateTime.Parse(dateMax).Date.AddDays(1); ;
            }
            list = list.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);
            totalCount = list.Count();
            list = list.OrderByDescending(m => m.add_time).Skip(iDisplayStart).Take(iDisplayLength);
            return list.ToList();
        }
        public bool SetCommentIsUse(int manageId, int id, int isUse)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作评论{1}状态为{2}", manageId, id, isUse));
            var entity = db.gw_goods_comments.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                entity.status = (byte)isUse;
                db.SaveChanges();
                return true;
            }
            return false;
        }

        #region 品牌
        public Response<IPagedList<GetBrandsOutput>> GetBrandsByPage(string brand_name, int brand_status, int page_index = 1, int page_size = 10)
        {
            Response<IPagedList<GetBrandsOutput>> result = new Response<IPagedList<GetBrandsOutput>>();
            try
            {

                var source = db.gw_base_brands
                    .Include(o => o.gw_company)
                    .Where(o => !o.deleted && o.company_id != null)
                    .Select(item => new GetBrandsOutput
                    {
                        add_time = item.add_time,
                        brand_id = item.id,
                        brand_name = item.name,
                        company_name = item.gw_company.name,
                        logo = item.logo,
                        sort = item.sort,
                        status = item.status,
                        is_top = item.is_top,
                    });

                //if (shop_id > -1)
                //{
                //    source = source.Where(s => s.shop_id == shop_id);
                //}
                if (brand_status != -1)
                {
                    source = source.Where(s => s.status == brand_status);
                }

                if (!string.IsNullOrWhiteSpace(brand_name))
                {
                    source = source.Where(s => s.brand_name.Contains(brand_name));
                }

                source = source.OrderBy(s => s.sort);

                var pagelist = new PagedList<GetBrandsOutput>(source, page_index, page_size);

                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }
        #endregion

    }
}
